package pers.chao.tool.http.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

	private String namePrefix;
	private final ThreadGroup group;
	private final boolean daemon;

	private final AtomicInteger THREAD_NUMBER = new AtomicInteger(0);

	public NamedThreadFactory() {
		this("Http-Async-Thread", false);
	}

	/**
	 * @param namePrefix 线程名前缀
	 */
	public NamedThreadFactory(String namePrefix) {
		this(namePrefix, false);
	}

	/**
	 * 
	 * @param namePrefix 线程名前缀
	 * @param daemon 是否daemon线程
	 */
	public NamedThreadFactory(String namePrefix, boolean daemon) {
		if (namePrefix != null) {
			this.namePrefix = namePrefix;
		}
		this.daemon = daemon;
		SecurityManager manager = System.getSecurityManager();
		group = (manager != null) ? manager.getThreadGroup() : Thread.currentThread().getThreadGroup();
	}

	@Override
	public Thread newThread(Runnable r) {
		String name = namePrefix + "-" + THREAD_NUMBER.getAndIncrement();
		Thread thread = new Thread(group, r, name, 0);
		if (thread.isDaemon() != daemon) {
			thread.setDaemon(daemon);
		}
		return thread;
	}

	public String getNamePrefix() {
		return namePrefix;
	}
}